package com.googlecode.strutson.utils

import org.apache.commons.io.FilenameUtils
import org.apache.commons.lang.SystemUtils

class EnvVariables {
    static String HOME = null
    static String APP_ROOT_DIR = null
    static String APP_NAME = null
    static String ROOT_PACKAGE = null
    static String ROOT_PACKAGE_DIR = null
    static String MODELS_DIR = null
    static String ACTIONS_DIR = null
    static String VIEWS_DIR = null
    static String SERVICES_DIR = null
    static String SERVICES_IMPL_DIR = null

    static String TARGET_DIR = null
    static String TARGET_ROOT_PACKAGE_DIR = null
    static String TARGET_MODELS_DIR = null


    static boolean load() {
        println 'Loading settings from pom.xml' 
        File pom = new File('pom.xml')
        if (!pom.exists()) {
            println 'Current directory does not contain an application. \'cd\' into the dir that contains the generated pom.xml file'
            return false
        }

        //parse pom.xml
        try {
            def project = new XmlParser().parse(new FileReader(pom))
            def maven = new groovy.xml.Namespace('http://maven.apache.org/POM/4.0.0')
            def groupId = project[maven.groupId][0]
            APP_NAME = project[maven.artifactId][0].text()
            setup(SystemUtils.userDir.path, groupId.text())
        } catch (Exception e) {
            println "Unable to parse [pom.xml], with error [${e.message}]"
            return false
        }

        return true;
    }

    static void setup(String appRoot, String rootPackage) {
        def sep = FilenameUtils.&separatorsToSystem
        def tailSep = {String path ->
            path.endsWith('/') || path.endsWith('\\') ? path : path + '/'
        }

        HOME = sep(tailSep(HOME))
        APP_ROOT_DIR = sep(tailSep(appRoot))
        ROOT_PACKAGE = rootPackage
        ROOT_PACKAGE_DIR = sep(tailSep(APP_ROOT_DIR + 'src/main/java/' + namespaceToDir(ROOT_PACKAGE)))
        VIEWS_DIR = sep(tailSep(APP_ROOT_DIR + 'src/main/webapp/WEB-INF/content'))
        MODELS_DIR = sep(tailSep(ROOT_PACKAGE_DIR + 'models'))
        ACTIONS_DIR = sep(tailSep(ROOT_PACKAGE_DIR + 'actions'))
        SERVICES_DIR = sep(tailSep(ROOT_PACKAGE_DIR + 'services'))
        SERVICES_IMPL_DIR = sep(tailSep(ROOT_PACKAGE_DIR + 'services/impl'))

        TARGET_DIR = sep(tailSep(APP_ROOT_DIR + 'target'))
        TARGET_ROOT_PACKAGE_DIR = sep(tailSep(TARGET_DIR + 'classes/' + namespaceToDir(ROOT_PACKAGE)))
        TARGET_MODELS_DIR = sep(tailSep(TARGET_ROOT_PACKAGE_DIR + 'models'))
    }

    static String namespaceToDir(String namespace) {
        return (namespace.replace('.', '/')) + '/'
    }
}